package com.birdboot.http;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class HttpServletRequest  {
    private Socket socket;
    private String method;   //请求方式
    private String uri;      //抽象路径
    private String protocol; //协议版本
    private Map<String,String> headers =new HashMap<>();
    public HttpServletRequest(Socket socket)throws IOException {
        this.socket = socket;
        parseRequestLine();
        parseHeaders();
        parseContent();
    }
    public void parseRequestLine()throws IOException{
        String line = readLine();
        System.out.println("请求行:"+line);
        //请求行:GET /index.html HTTP/1.1
        String[] data = line.split("\\s");
        method = data[0];
        uri = data[1];
        protocol = data[2];
        System.out.println(method+","+uri+","+protocol);
    }

    public void parseHeaders()throws IOException{
        //2处理请求
        while (true){
            String line = readLine();
            if(line.isEmpty()){
                break;
            }
            //System.out.println("消息头:"+line);
            String[] split = line.split(":\\s");
            if(split.length>=2){
                headers.put(split[0],split[1]);
            }else {
                System.out.println(split.length);
            }


        }
        System.out.println("headers:"+ headers);
    }
    //解析正文
    public void parseContent(){

    }


    public Socket getSocket() {
        return socket;
    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }

    public String getHeader(String key) {
        return headers.get(key);
    }




    private String readLine() throws IOException {
        InputStream in = socket.getInputStream();
        int d;
        StringBuilder builder = new StringBuilder();//保存拼接后的一行字符串
        char cur='a',pre='a';//cur表示本次读取的字符  pre表示上次读取的字符
        while((d = in.read())!=-1){
            cur = (char)d;//将本次读取的字符赋值给cur
            if(pre==13 && cur==10){//判断上次是否读取的回车符,本次是否为换行符
                break;//若连续读取了回车+换行就停止读取(一行结束了)
            }
            builder.append(cur);
            pre=cur;//在读取下一个字符前,将本次读取的字符记作"上次读取的字符"
        }
        return builder.toString().trim();

    }

}
